<template>
    <el-container style="height: 820px; border: 1px solid #eee;padding: 5px">
        <el-main>
            <el-table
                    :data="departmentTable.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
                    style="width: 100%" height="720px">
                <el-table-column width="180px"
                                 label="部门名称"
                                 prop="name">
                </el-table-column>
                </el-table-column>
                <el-table-column
                        label="备注"
                        prop="remark">
                </el-table-column>
                <el-table-column
                        label="创建日期"
                        prop="created_at">
                </el-table-column>
                <el-table-column
                        label="更新日期"
                        prop="updated_at">
                </el-table-column>
                <el-table-column
                        align="right" width="300px">
                    <template slot="header" slot-scope="scope">
                        <el-input
                                v-model="search"
                                size="mini"
                                placeholder="输入关键字搜索"/>
                    </template>
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">更新
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">刪除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer>
            <el-form inLine="true">
                <el-button @click="createDepartment" type="primary">新增部门</el-button>
                <el-button @click="exportStaff" type="primary">导出所有人员</el-button>
                <el-checkbox v-model="split2sheet">分部门导出</el-checkbox>
            </el-form>
        </el-footer>
        <el-dialog :title="(isEdit?'更新':'新增')+'部门信息'" width="40%"
                   :visible.sync="dialogFormVisible">
            <el-form :model="form" v-loading="loading" :rules="rules" ref="form">
                <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
                    <el-input v-model="form.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleForm">{{isEdit?'更新':'新增'}}</el-button>
            </div>
        </el-dialog>
    </el-container>
</template>
<script>
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    export default{
        props: ['departments'],
        data(){
            return {
                departmentTable: [],
                search: '',
                split2sheet: false,
                isEdit: false,
                formLabelWidth: '200px',
                dialogFormVisible: false,
                dataDialogVisible: false,
                Staff: [],
                loading: false,
                form: {
                    id: '',
                    name: '',
                    remark: ''
                },
                rules: {
                    name: [
                        {required: true, message: '必填项', trigger: 'blur'},
                        {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
                    ],
                    remark: [
                        {max: 255, message: '长度不大于255个字符', trigger: 'blur'}
                    ]
                },
            }
        },
        created(){
            if (this.departments) {
                this.departmentTable = this.departments;
            } else {
                this.getDepartments();
            }
        },
        methods: {
            getDepartments(){
                axios.get('api/v1/department').then(result => {
                    this.departmentTable = result.data;
                });
            },
            createDepartment(){
                if (this.$refs['form']) {
                    this.$refs['form'].resetFields();
                } else {
                    this.form.name = '';
                    this.form.remark = '';
                }
                this.isEdit = false;
                this.dialogFormVisible = true;
                console.log(this.form);
            },
            handleEdit(index, row) {
                this.form = row;
                this.dialogFormVisible = true;
                this.isEdit = true;
            },
            handleDelete(index, row) {
                axios.get('api/v1/department/' + row.id).then(
                    result => {
                        console.log(result);
                        if (result.data.staff_count > 0) {
                            this.$confirm(row.name + '系统记录有人员隶属此部门，如果删除那么这些人员所属部门将会变成未指定！', '删除提示').then(() => {
                                axios.delete('api/v1/department/' + row.id).then(result => {
                                    this.$notify.success('删除成功');
                                    this.getDepartments();
                                }).catch(
                                    error => {
                                        this.$notify.error('删除失败');
                                        if (error.response) {
                                            console.log(error.response.data); // => the response payload
                                        }
                                    });
                            }).catch(action => {
                                //if(action=='cancel')console.log('cancel');
                            });
                        } else {
                            this.$confirm('确定删除' + row.name, '删除提示').then(() => {
                                axios.delete('api/v1/department/' + row.id).then(result => {
                                    this.$notify.success('删除成功');
                                    this.getDepartments();
                                }).catch(
                                    error => {
                                        this.$notify.error('删除失败');
                                        if (error.response) {
                                            console.log(error.response.data); // => the response payload
                                        }
                                    });
                            }).catch(action => {
                                //if(action=='cancel')console.log('cancel');
                            });
                        }
                    }).catch(error => {
                        if (error.response) {
                            console.log(error.response.data); // => the response payload
                        }
                    }
                );
            },
            handleForm(){
                if (this.isEdit) {
                    axios.put('api/v1/department/' + this.form.id, this.form).then(result => {
                        this.dialogFormVisible = false;
                        this.$notify.success('更新成功');
                        this.getDepartments();
                    }).catch(error => {
                        this.$notify.error('更新失败');
                        console.log(error);
                    });
                }
                else {
                    axios.post('api/v1/department', this.form).then(result => {
                        this.dialogFormVisible = false;
                        this.$notify.success('新增成功');
                        this.getDepartments();
                    }).catch(error => {
                        this.$notify.error('新增失败');
                        if (error.response) {
                            console.log(error.response.data); // => the response payload
                        }
                    });
                }
            },
            exportStaff(){
                const loading = this.$loading({
                    lock: true,
                    text: '正在导出',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                axios.get('api/v1/staff').then(result => {
                    var wb = XLSX.utils.book_new();
                    var data = result.data;
                    var Staff = [];
                    var dpt_id = 0;
                    var i = 0;
                    var sheetName='';
                    if (data && data.length > 0) {
                        if (this.split2sheet)
                        {
                            data.forEach(c => {
                                var dpt_name=c.department?c.department.name:'未指定';
                                var dorm_code=c.dorm?c.dorm.code:'';
                                var sex='';
                                if(c.sex<2)sex=(c.sex==1?'男':'女');
                                if (dpt_id == 0) {//第一个部门
                                    wb.SheetNames.push(dpt_name);
                                    sheetName=dpt_name;
                                    Staff.push({姓名:c.name,性别:sex,身份证:c.id_card,部门:dpt_name,宿舍:dorm_code});
                                    dpt_id = c.department_id;
                                }
                                else
                                {
                                    if (c.department_id != dpt_id) {//new department
                                        var ws = XLSX.utils.json_to_sheet(Staff);
                                        wb.Sheets[sheetName] = ws;
                                        wb.SheetNames.push(dpt_name);
                                        sheetName=dpt_name;
                                        Staff = [];
                                        Staff.push({姓名:c.name,性别:sex,身份证:c.id_card,部门:dpt_name,宿舍:dorm_code});
                                        dpt_id = c.department_id;
                                    }else{
                                        Staff.push({姓名:c.name,性别:sex,身份证:c.id_card,部门:dpt_name,宿舍:dorm_code});
                                    }
                                }
                                i++;
                                if (i == data.length) {
                                    var ws = XLSX.utils.json_to_sheet(Staff);
                                    wb.Sheets[sheetName] = ws;
                                }

                            });

                        } else {
                            wb.SheetNames.push('all_staff');
                            data.forEach(c => {
                                var dpt_name=c.department?c.department.name:'';
                                var dorm_code=c.dorm?c.dorm.code:'';
                                var sex='';
                                if(c.sex<2)sex=(c.sex==1?'男':'女');
                                Staff.push({姓名:c.name,性别:sex,身份证:c.id_card,部门:dpt_name,宿舍:dorm_code});
                            });

                            var ws = XLSX.utils.json_to_sheet(Staff);
                            wb.Sheets['all_staff'] = ws;
                        }
                    }

                    /* get binary string as output */
                    let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
                    try {
                        var fileName='所有人员信息'+(this.split2sheet?'-分部门':'')+'.xlsx';
                        FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), fileName);
                    } catch (e) {
                        if (typeof console !== 'undefined')
                            console.log(e, wbout)
                    }
                    loading.close();
                });
            },
        }
    }
</script>
